<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-10-20
 * Time: 21:38
 */

namespace app\common\job;


use app\api\model\mp\v1\OrderSubscribeMessage;
use app\common\enum\OrderEnum;
use think\queue\Job;
use app\common\model\Order as OrderModel;

class PayRefundNotifyQueue
{
    /**
     * fire是消息队列默认调用的方法
     * @param Job $job 当前的任务对象
     * @param array|mixed $data 发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        //有效消息到达消费者时可能已经不再需要执行了
        if (!$this->checkJob($data)) {
            $job->delete();
            return;
        }
        //执行业务处理
        if ($this->doJob($data)) {
            $job->delete();//任务执行成功后删除
            echo '[退款成功通知]订单'.$data['decode']['out_trade_no'].'通知成功'.PHP_EOL;
        } else {
            //检查任务重试次数
            if ($job->attempts() > 3) {
                echo '[退款成功通知]订单'.$data['decode']['out_trade_no'].'通知失败，达到最大重试数'.PHP_EOL;
                $job->delete();
            }
        }
    }

    /**
     * 接收队列消息的失败回调和告警
     * @param $e 消息队列出错的相关信息
     */
    public function failed($e)
    {
        print_r('消息队列出错，出错信息如下');
        var_dump($e);
    }

    /**
     * 简单当前订单是否需要执行本消息
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean 任务执行的结果
     */
    private function checkJob($data)
    {
        $decode_data = $data["decode"];

        // 判断订单是否存在或者是否为已提交状态
        if (OrderModel::checkOrderStatusByOrderNo($decode_data['out_trade_no'],OrderEnum::CREATE_REFUND)) {
            return true;
        }

        (new OrderModel())->db()->getConnection()->close();
        return false;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     */
    private function doJob($data)
    {
        // 实际业务流程处理
        $decode_data = $data["decode"];
        $is_send_template = $data['is_send_template'];

        // 更新订单信息
        $updateData = [
            'order_end_time' => time()
        ];

        switch ($decode_data['refund_status']) {
            case 'SUCCESS' :
                $updateData['status'] = OrderEnum::REFUND_SUCCESS;
                break;
            case 'CHANGE' :
                $updateData['status'] = OrderEnum::REFUND_CHANGE;
                break;
            case 'REFUNDCLOSE' :
                $updateData['status'] = OrderEnum::REFUND_CLOSE;
                break;
        }

        // 更新订单信息
        OrderModel::updateByOrderNo($decode_data['out_trade_no'], ['status', 'order_end_time'], $updateData);

        if ($updateData['status'] == OrderEnum::REFUND_SUCCESS) {
            // 向用户发送退款成功消息模版
            $orderData = OrderModel::getOrderDataByOrderNo($decode_data['out_trade_no'],['title','refund_desc','refund_amount','allow_refund_subscribe','refund_create_time']);
//
//                // 根据不同的订单类型处理不同处理
//                switch ($orderData['type']) {
//                    case OrderType::H5_TEMPLATE :
//                        // 退款成功后删除该用户的模版数据
//                        H5TemplateDataModel::where(['order_id' => $orderData['id']])
//                            ->find()
//                            ->delete();
//                        break;
//                }

            if ($is_send_template && $orderData['allow_refund_subscribe'] === 1) {
//                    Log::record('|refund_create_time' . $orderData['refund_create_time'], 'error');
                (new OrderSubscribeMessage())->sendOrderSubscribeMessage(
                    'refund',
                    $orderData['user']['openid'],
                    [
                        'order_no' => $orderData['order_no'],
                        'title' => $orderData['title'],
                        'refund_desc' => $orderData['refund_desc'],
                        'refund_amount' => $orderData['refund_amount'],
                        'refund_create_time' => $orderData['refund_create_time']
                    ]);
            }

        }
        (new OrderModel())->db()->getConnection()->close();
        return true;
    }
}